package com.example.hzly.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.hzly.dto.StoryDTO;
import com.example.hzly.entity.Story;
import com.example.hzly.entity.StoryComment;
import com.example.hzly.entity.StoryTag;
import com.example.hzly.entity.User;
import com.example.hzly.mapper.StoryCommentMapper;
import com.example.hzly.mapper.StoryMapper;
import com.example.hzly.mapper.UserMapper;
import com.example.hzly.service.StoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.sql.Date;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class StoryServiceImpl extends ServiceImpl<StoryMapper, Story> implements StoryService {

    @Autowired
    private StoryMapper storyMapper;
    
    @Autowired
    private StoryCommentMapper storyCommentMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public StoryDTO selectStoryById(Long id) {
        Story story = storyMapper.selectStoryById(id);
        incrementViews(id);
        return convertToDTO(story);
    }

    @Override
    public IPage<StoryDTO> getStoryList(Page<Story> page) {
        // 执行分页查询
        IPage<Story> storyPage = storyMapper.selectStoriesPage(page);
        // 转换结果
        return storyPage.convert(this::convertToDTO);
    }

    @Override
    public void incrementViews(Long id) {
        storyMapper.incrementViews(id);
    }

    @Override
    public IPage<StoryDTO> getHotStories(Page<Story> page) {
        // 执行分页查询
        IPage<Story> storyPage = storyMapper.selectHotStories(page);
        // 转换结果
        return storyPage.convert(this::convertToDTO);
    }


    private StoryDTO convertToDTO(Story story) {
        if (story == null) {
            return null;
        }

        StoryDTO dto = new StoryDTO();
        dto.setId(story.getId());
        dto.setTitle(story.getTitle());
        dto.setExcerpt(story.getExcerpt());
        dto.setContent(story.getContent());
        dto.setCategory(story.getCategory());
        dto.setCoverImage(story.getCoverImage());
        dto.setPublishDate(story.getPublishDate());
        dto.setUpdateDate(story.getUpdateDate());
        dto.setViews(story.getViews());
        dto.setLikes(story.getLikes());
        dto.setStatus(story.getStatus());

        // 处理标签
        if (story.getTags() != null && !story.getTags().isEmpty()) {
            List<String> tagNames = story.getTags().stream()
                    .map(StoryTag::getTagName)
                    .collect(Collectors.toList());
            dto.setTags(tagNames);
        }

        // 处理评论
        if (story.getComments() != null && !story.getComments().isEmpty()) {
            List<StoryDTO.CommentDTO> commentDTOs = story.getComments().stream()
                    .filter(comment -> comment.getStatus() != null && comment.getStatus() == 1)
                    .map(comment -> {
                        StoryDTO.CommentDTO commentDTO = new StoryDTO.CommentDTO();
                        commentDTO.setId(comment.getId());
                        commentDTO.setContent(comment.getContent());
                        commentDTO.setCreateTime(comment.getCreateTime());
                        commentDTO.setLikes(comment.getLikes());

                        if (comment.getUser() != null) {
                            StoryDTO.UserDTO userDTO = new StoryDTO.UserDTO();
                            userDTO.setId(comment.getUser().getId());
                            userDTO.setName(comment.getUser().getName());
                            userDTO.setAvatar(comment.getUser().getAvatar());
                            commentDTO.setUser(userDTO);
                        }

                        return commentDTO;
                    })
                    .collect(Collectors.toList());
            dto.setComments(commentDTOs);
        }

        // 处理作者信息
        if (story.getAuthor() != null) {
            StoryDTO.AuthorDTO authorDTO = new StoryDTO.AuthorDTO();
            authorDTO.setId(story.getAuthor().getId());
            authorDTO.setName(story.getAuthor().getName());
            authorDTO.setAvatar(story.getAuthor().getAvatar());
            authorDTO.setDescription(story.getAuthor().getDescription());
            dto.setAuthor(authorDTO);
        }

        // 处理目的地信息
        if (story.getDestination() != null) {
            StoryDTO.Destination destinationDTO = new StoryDTO.Destination();
            destinationDTO.setId(story.getDestination().getId());
            destinationDTO.setName(story.getDestination().getName());
            destinationDTO.setDescription(story.getDestination().getDescription());
            destinationDTO.setLocation(story.getDestination().getLocation());
            destinationDTO.setImageUrl(story.getDestination().getImageUrl());
            dto.setDestination(destinationDTO);
        }

        // 处理相关故事
        if (story.getRelatedStories() != null && !story.getRelatedStories().isEmpty()) {
            List<StoryDTO.RelatedStoryDTO> relatedStoryDTOs = story.getRelatedStories().stream()
                    .map(relatedStory -> {
                        StoryDTO.RelatedStoryDTO relatedDTO = new StoryDTO.RelatedStoryDTO();
                        relatedDTO.setId(relatedStory.getId());
                        relatedDTO.setTitle(relatedStory.getTitle());
                        relatedDTO.setExcerpt(relatedStory.getExcerpt());
                        relatedDTO.setCoverImage(relatedStory.getCoverImage());
                        if (relatedStory.getAuthor() != null) {
                            relatedDTO.setAuthorName(relatedStory.getAuthor().getName());
                        }
                        return relatedDTO;
                    })
                    .collect(Collectors.toList());
            dto.setRelatedStories(relatedStoryDTOs);
        }

        return dto;
    }

    private StoryDTO.CommentDTO convertToCommentDTO(StoryComment comment) {
        StoryDTO.CommentDTO dto = new StoryDTO.CommentDTO();
        dto.setId(comment.getId());
        dto.setContent(comment.getContent());
        dto.setCreateTime(comment.getCreateTime());
        dto.setLikes(comment.getLikes());

        if (comment.getUser() != null) {
            StoryDTO.UserDTO userDTO = new StoryDTO.UserDTO();
            userDTO.setId(comment.getUser().getId());
            userDTO.setName(comment.getUser().getName());
            userDTO.setAvatar(comment.getUser().getAvatar());
            dto.setUser(userDTO);
        }

        return dto;
    }


    @Override
    public IPage<StoryDTO> getStoriesByCategory(String category, Page<Story> page) {
        IPage<Story> storyPage = storyMapper.selectStoriesByCategory(category, page);
        return storyPage.convert(this::convertToDTO);
    }

    @Override
    public IPage<StoryDTO> getStoriesByDestination(Long destinationId, Page<Story> page) {
        IPage<Story> storyPage = storyMapper.selectStoriesByDestination(destinationId, page);
        return storyPage.convert(this::convertToDTO);
    }

    @Override
    public IPage<StoryDTO> getStoriesByAuthor(Long authorId, Page<Story> page) {
        IPage<Story> storyPage = storyMapper.selectStoriesByAuthor(authorId, page);
        return storyPage.convert(this::convertToDTO);
    }

    @Override
    public IPage<StoryDTO> searchStories(String keyword, Page<Story> page) {
        IPage<Story> storyPage = storyMapper.searchStories(keyword, page);
        return storyPage.convert(this::convertToDTO);
    }

    @Override
    public List<String> getAllCategories() {
        return storyMapper.selectAllCategories();
    }

    @Override
    public Map<String, Object> getStoryStats() {
        Map<String, Object> stats = new HashMap<>();

        // 获取总故事数
        int totalCount = (int) count();
        stats.put("totalCount", totalCount);

        // 获取分类统计
        List<Map<String, Object>> categoryStats = storyMapper.selectCategoryStats();
        stats.put("categoryStats", categoryStats);

        // 获取热门故事统计
        int hotCount = storyMapper.selectHotCount();
        stats.put("hotCount", hotCount);

        // 获取最近一周发布的故事数
        int recentCount = storyMapper.selectRecentCount();
        stats.put("recentCount", recentCount);

        return stats;
    }

    @Override
    public void incrementLikes(Long id) {
        storyMapper.incrementLikes(id);
    }

    @Override
    public void addComment(StoryComment comment) {
        // 设置评论状态为正常
        comment.setStatus(1);
        // 设置评论时间为当前时间
        comment.setCreateTime(new Date(System.currentTimeMillis()));
        // 初始化点赞数为0
        comment.setLikes(0);

        // 保存评论
        storyCommentMapper.insert(comment);
    }

    @Override
    public List<StoryDTO> getRelatedStories(Long id, Integer size) {
        // 将 selectRelatedStories 修改为 getRelatedStories
        List<Story> stories = storyMapper.getRelatedStories(id, size);
        return stories.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public List<StoryDTO> getLatestStories(Integer size) {
        List<Story> stories = storyMapper.selectLatestStories(size);
        return stories.stream().map(this::convertToDTO).collect(Collectors.toList());
    }

    @Override
    public void deleteComment(Long commentId, Long userId) {
        StoryComment comment = storyCommentMapper.selectById(commentId);
        if (comment == null || !userId.equals(comment.getUserId())) {
            throw new RuntimeException("只能删除自己的评论");
        }
        storyCommentMapper.deleteById(commentId);
    }

    @Override
    public List<StoryDTO.CommentDTO> getNestedComments(Long storyId) {
        List<StoryComment> allComments = storyCommentMapper.selectCommentsByStoryId(storyId);
        // 补全用户信息
        for (StoryComment c : allComments) {
            if (c.getUser() == null && c.getUserId() != null) {
                User user = userMapper.selectById(c.getUserId());
                c.setUser(user);
            }
        }
        // 构建id->DTO映射
        Map<Long, StoryDTO.CommentDTO> map = new HashMap<>();
        List<StoryDTO.CommentDTO> roots = new ArrayList<>();
        for (StoryComment c : allComments) {
            StoryDTO.CommentDTO dto = convertToCommentDTO(c);
            dto.setParentId(c.getParentId());
            map.put(dto.getId(), dto);
        }
        for (StoryDTO.CommentDTO dto : map.values()) {
            if (dto.getParentId() == null) {
                roots.add(dto);
            } else {
                StoryDTO.CommentDTO parent = map.get(dto.getParentId());
                if (parent != null) {
                    if (parent.getReplies() == null) parent.setReplies(new ArrayList<>());
                    parent.getReplies().add(dto);
                }
            }
        }
        return roots;
    }
}
